﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using Frame.Lib.Common;
using Frame.Lib.Core.Attach;
using Cms.Entity.Article;
using Cms.BLL.Menu;
using Frame.Lib.Utilities;
using Cms.BLL.Article;
using Cms.DAL;

namespace Cms.Admin.Article
{
    public partial class Edit : PageEdit
    {
        protected string Content;

        private ArticleBO _article;
        private ArticleBO Article
        {
            get
            {
                if (_article == null)
                {
                    _article = new ArticleBO();
                }
                return _article;
            }
        }
        private string MenuID
        {
            get
            {
                return Request.QueryString["MenuID"];
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            JSUtil.SetDivHeight(pnlMain.ClientID, 32);

            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(PKID))
                {
                    DispInfo();
                }
                else
                {
                    hidMenuIDs.Value = MenuID;
                    txtMenuName.Text = (new MenuBO()).GetName(MenuID);
                    Source.Text = "http://";
                    trImages.Visible = false;
                }
            }
            AddAttr();
        }

        private void AddAttr()
        {
            JSUtil.ShowTreeDlg(hidMenuIDs, txtMenuName, CTableName.Menu, "选择栏目",true);
            JSUtil.ClickBtn(lnkSave, btnSave);
        }

        private void DispInfo()
        {
            ArticleInfo info = this.Article.GetInfo(this.PKID);
            EntityUtil.SetControl(pnlMain, info);
            hidMenuIDs.Value = info.MenuID.ToString();
            txtMenuName.Text = info.MenuName;

            if (info.Content != null)
            {
                this.Content = info.Content.Replace("'", "\\'").Replace("\r\n", " ");
            }

            if (!string.IsNullOrEmpty(info.SmallImage))
            {
                imgTitlePicture.Visible = true;
                imgTitlePicture.ImageUrl = info.SmallImageAbsPath;
                lnkTitlePicture.HRef = info.BigImageAbsPath;
                btnDelete.Visible = true;
            }
            else
            {
                imgTitlePicture.Visible = false;
                btnDelete.Visible = false;
            }
            rptAttach.DataSource = info.Attachs;
            rptAttach.DataBind();

            rptPicture.DataSource = info.Pictures;
            rptPicture.DataBind();

            if (info.Pictures.Count > 0)
            {
                trImages.Visible = true;
            }
            else
            {
                trImages.Visible = false;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ArticleInfo info = Article.GetInfo(PKID);
           
            EntityUtil.SetEntity(pnlMain, info);           

            if (string.IsNullOrEmpty(PKID))
            {
                info.MenuID = int.Parse(MenuID);
                info.MenuName = new MenuBO().GetName(MenuID);
                info.InputTime = DateTime.Now;
                info.Orders = this.Article.GetMaxOrder();
            }
            info.UpdateTime = DateTime.Now;
            info.CreatorID = AppSession.UserID;
            info.CreatorName = AppSession.UserName;
            if (fileTitlePicture.FileName != "")
            {
                if (!string.IsNullOrEmpty(info.SmallImage))
                {
                    Article.DeleteTitlePicture(info.ID);
                }

                this.Article.SaveImage(info, fileTitlePicture.PostedFile);
               
            }

            
            this.Article.Save(info);//先不保存内容，要替换图片的地址

            info.Content = Request["content"];
            info.KeyWords = this.KeyWords.Text.Replace("，", ",");
            

            UserImage userImage = new UserImage(CTableName.ArticlePicture);

            ImageBO picture = new ImageBO(CTableName.ArticlePicture);
            AttachBO attach = new AttachBO(CTableName.ArticleAttach);
            
            foreach (string key in Request.Files.Keys)
            {
               
                if (key.Contains("pic"))
                {
                    //判断图片格式
                    string extention = System.IO.Path.GetExtension(Request.Files[key].FileName).ToLower();
                    if (extention == ".jpg" || extention == ".png" || extention == ".gif" || extention == ".bmp")
                    {
                        System.Drawing.Bitmap img = new System.Drawing.Bitmap(Request.Files[key].InputStream);
                        ImageInfo pictureInfo = new ImageInfo();
                        pictureInfo.Name = System.IO.Path.GetFileName(Request.Files[key].FileName);
                        pictureInfo.BindID = info.ID;
                        pictureInfo.InputTime = DateTime.Now;
                        pictureInfo.Width = img.Width;
                        pictureInfo.Height = img.Height;
                        pictureInfo.Size = (int)Request.Files[key].InputStream.Length;
                        pictureInfo.Orders = picture.GetMaxOrder(info.ID);
                       

                        this.Article.SaveImage(pictureInfo, Request.Files[key], info.MenuInfo);

                        info.Content = info.Content.Replace("[img]" + key + "[/img]", "<img src='" + AppSetting.ImageDomain + pictureInfo.BigImageAbsPath + "' alt='" + pictureInfo.Name + "' />");


                        picture.Save(pictureInfo);
                    }
                }
                else if(key.Contains("attach"))
                {
                    attach.Save(Request.Files[key], info.ID);
                }
            }

            if (info.Summary.Trim() == "")
            {
                //string txt = Regex.Replace(info.Content, "<[^>]+>", "").Replace("&nbsp;", " ");
                //int maxLength = txt.Length;
                //info.Summary = txt.Substring(0, maxLength);
            }

            info.Summary = Summary.Text;
            this.Article.Save(info);//保存更换过图片地址的文章


            string url = "List.aspx?MenuID=" + Server.UrlEncode(StrUtil.EncryptDES(info.MenuID.ToString()));

            string script = "alert('保存成功');location.href='" + url + "';";
            JSUtil.ResponseJS(script);
        }

        protected void rptAttach_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            AttachBO attach = new AttachBO(CTableName.ArticleAttach);
            attach.Delete(Convert.ToInt32(e.CommandArgument));
            DispInfo();
        }

        protected void rptPicture_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            ImageBO picture = new ImageBO(CTableName.ArticlePicture);
            picture.Delete(Convert.ToInt32(e.CommandArgument));
            DispInfo();
        }

        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            ArticleInfo info = this.Article.GetInfo(this.PKID);

            Article.DeleteTitlePicture(info.ID);

            info.SmallImage = null;

            Article.Save(info);

            DispInfo();
        }
    }
}
